<template>
  <div class="karma-engine-page">
    <!-- 面包屑导航 -->
    <div class="breadcrumb-wrapper">
      <a-breadcrumb>
        <a-breadcrumb-item>
          <a @click="goBack">因果业力系统</a>
        </a-breadcrumb-item>
        <a-breadcrumb-item>业力计算引擎</a-breadcrumb-item>
      </a-breadcrumb>
      <a-button type="text" @click="goBack" class="back-button">
        <LeftOutlined />
        返回上级
      </a-button>
    </div>

    <!-- 页面标题 -->
    <div class="ancient-title">业力计算引擎</div>

    <!-- 整体统计概览 -->
    <a-row :gutter="[24, 24]" class="stats-row">
      <a-col :xs="12" :sm="6">
        <a-card class="stat-card">
          <a-statistic title="总计算次数" :value="totalCalculations" :value-style="{ color: '#1890ff', fontSize: '24px' }" suffix="次" />
        </a-card>
      </a-col>
      <a-col :xs="12" :sm="6">
        <a-card class="stat-card">
          <a-statistic title="预测准确率" :value="predictionAccuracy" :value-style="{ color: '#52c41a', fontSize: '24px' }" suffix="%" />
        </a-card>
      </a-col>
      <a-col :xs="12" :sm="6">
        <a-card class="stat-card">
          <a-statistic title="活跃规则数" :value="activeRulesCount" :value-style="{ color: '#722ed1', fontSize: '24px' }" suffix="条" />
        </a-card>
      </a-col>
      <a-col :xs="12" :sm="6">
        <a-card class="stat-card">
          <a-statistic title="待报应人数" :value="pendingRetributionCount" :value-style="{ color: '#fa541c', fontSize: '24px' }" suffix="人" />
        </a-card>
      </a-col>
    </a-row>

    <!-- 主要功能区域 -->
    <a-row :gutter="[24, 24]" class="function-row">
      <!-- 业力积分规则管理 -->
      <a-col :xs="24" :lg="12">
        <a-card title="业力积分规则" :bordered="false" class="rules-card">
          <a-tabs>
            <a-tab-pane key="good" tab="善行规则">
              <a-table :columns="goodRulesColumns" :data-source="goodRulesData" :pagination="false" size="small">
                <template #bodyCell="{ column, record }">
                  <template v-if="column.key === 'score'">
                    <span class="score-positive">+{{ record.score }}</span>
                  </template>
                  <template v-else-if="column.key === 'level'">
                    <a-tag :color="getLevelColor(record.level)">{{ record.level }}</a-tag>
                  </template>
                  <template v-else-if="column.key === 'actions'">
                    <a-button type="link" size="small" @click="editRule('good', record.key)">编辑</a-button>
                  </template>
                </template>
              </a-table>
            </a-tab-pane>
            <a-tab-pane key="bad" tab="恶行规则">
              <a-table :columns="badRulesColumns" :data-source="badRulesData" :pagination="false" size="small">
                <template #bodyCell="{ column, record }">
                  <template v-if="column.key === 'score'">
                    <span class="score-negative">{{ record.score }}</span>
                  </template>
                  <template v-else-if="column.key === 'level'">
                    <a-tag :color="getLevelColor(record.level)">{{ record.level }}</a-tag>
                  </template>
                  <template v-else-if="column.key === 'actions'">
                    <a-button type="link" size="small" @click="editRule('bad', record.key)">编辑</a-button>
                  </template>
                </template>
              </a-table>
            </a-tab-pane>
          </a-tabs>
        </a-card>
      </a-col>

      <!-- 个人业力计算器 -->
      <a-col :xs="24" :lg="12">
        <a-card title="个人业力计算器" :bordered="false" class="calculator-card">
          <a-form layout="vertical">
            <a-form-item label="选择人员">
              <a-select v-model:value="selectedPerson" placeholder="请选择要计算的人员" @change="calculatePersonKarma">
                <a-select-option v-for="person in allPersons" :key="person.personId" :value="person.personId">
                  {{ person.personName }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-form>

          <div v-if="selectedPersonData" class="karma-calculation-result">
            <a-descriptions title="业力计算结果" :column="1" size="small">
              <a-descriptions-item label="善行积分">
                <span class="score-positive">+{{ selectedPersonData.goodKarma }}</span>
              </a-descriptions-item>
              <a-descriptions-item label="恶行积分">
                <span class="score-negative">-{{ selectedPersonData.badKarma }}</span>
              </a-descriptions-item>
              <a-descriptions-item label="净业力">
                <span :class="selectedPersonData.netKarma >= 0 ? 'score-positive' : 'score-negative'"> {{ selectedPersonData.netKarma >= 0 ? '+' : '' }}{{ selectedPersonData.netKarma }} </span>
              </a-descriptions-item>
              <a-descriptions-item label="抵消比例"> {{ selectedPersonData.offsetPercentage }}% </a-descriptions-item>
              <a-descriptions-item label="业力等级">
                <a-tag :color="getKarmaLevel(selectedPersonData.netKarma).color">
                  {{ getKarmaLevel(selectedPersonData.netKarma).level }}
                </a-tag>
              </a-descriptions-item>
            </a-descriptions>

            <a-progress :percent="Number(selectedPersonData.offsetPercentage)" :status="selectedPersonData.canOffset ? 'success' : 'exception'" :format="(percent) => `善恶抵消 ${percent}%`" />
          </div>
        </a-card>
      </a-col>
    </a-row>

    <!-- 业力趋势分析 -->
    <a-row :gutter="[24, 24]" class="analysis-row">
      <a-col :span="24">
        <a-card title="业力趋势分析" :bordered="false" class="trend-card">
          <a-tabs v-model:activeKey="activeTab" @change="handleTabChange">
            <a-tab-pane key="overall" tab="整体趋势">
              <div class="chart-container">
                <div ref="overallTrendChart" class="echarts-wrapper" v-show="!chartsLoading"></div>
                <div v-if="chartsLoading" class="chart-loading">
                  <a-spin size="large">
                    <template #indicator>
                      <div class="custom-spinner">⚖️</div>
                    </template>
                  </a-spin>
                  <p>正在分析业力趋势...</p>
                </div>
                <div class="chart-description">
                  <p>展示最近6个月善恶业力的整体变化趋势，帮助了解业力发展方向</p>
                </div>
              </div>
            </a-tab-pane>
            <a-tab-pane key="distribution" tab="等级分布">
              <div class="chart-container">
                <div ref="distributionChart" class="echarts-wrapper" v-show="!chartsLoading"></div>
                <div v-if="chartsLoading" class="chart-loading">
                  <a-spin size="large">
                    <template #indicator>
                      <div class="custom-spinner">🔮</div>
                    </template>
                  </a-spin>
                  <p>正在统计等级分布...</p>
                </div>
                <div class="chart-description">
                  <p>展示当前所有人员的业力等级分布情况，一目了然地查看各等级人数占比</p>
                </div>
              </div>
            </a-tab-pane>
            <a-tab-pane key="prediction" tab="趋势预测">
              <div class="chart-container">
                <div ref="predictionChart" class="echarts-wrapper" v-show="!chartsLoading"></div>
                <div v-if="chartsLoading" class="chart-loading">
                  <a-spin size="large">
                    <template #indicator>
                      <div class="custom-spinner">🔭</div>
                    </template>
                  </a-spin>
                  <p>正在预测未来趋势...</p>
                </div>
                <div class="chart-description">
                  <p>基于历史数据预测未来6个月的业力趋势，包含善行、恶行及净业力变化</p>
                </div>
              </div>
            </a-tab-pane>
          </a-tabs>
        </a-card>
      </a-col>
    </a-row>

    <!-- 报应时机预测 -->
    <a-row :gutter="[24, 24]" class="prediction-row">
      <a-col :span="24">
        <a-card title="报应时机预测系统" :bordered="false" class="prediction-card">
          <a-form layout="inline" style="margin-bottom: 16px">
            <a-form-item label="选择人员">
              <a-select v-model:value="predictionPerson" placeholder="请选择要预测的人员" style="width: 200px" @change="handlePredictRetribution">
                <a-select-option v-for="person in evilPersons" :key="person.personId" :value="person.personId"> {{ person.personName }} ({{ person.totalScore }}分) </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="batchPredictRetribution"> 批量预测 </a-button>
            </a-form-item>
          </a-form>

          <div v-if="retributionPrediction" class="retribution-result">
            <a-alert :message="`${getCurrentPersonName(predictionPerson)} 的报应预测`" :type="getRetributionAlertType(retributionPrediction.probability)" show-icon>
              <template #description>
                <a-descriptions :column="2" size="small">
                  <a-descriptions-item label="报应类型">{{ getRetributionTypeName(retributionPrediction.type) }}</a-descriptions-item>
                  <a-descriptions-item label="时间范围">{{ retributionPrediction.timeRange }}</a-descriptions-item>
                  <a-descriptions-item label="发生概率">{{ (retributionPrediction.probability * 100).toFixed(1) }}%</a-descriptions-item>
                  <a-descriptions-item label="严重程度">{{ retributionPrediction.severity }}分</a-descriptions-item>
                  <a-descriptions-item label="近期恶行">{{ retributionPrediction.recentBadDeeds }}件</a-descriptions-item>
                </a-descriptions>
              </template>
            </a-alert>

            <a-progress :percent="retributionPrediction.probability * 100" :status="retributionPrediction.probability > 0.6 ? 'exception' : 'normal'" :format="(percent) => `概率 ${percent.toFixed(1)}%`" style="margin-top: 16px" />
          </div>

          <a-table :columns="retributionColumns" :data-source="allRetributionPredictions" :pagination="{ pageSize: 10 }" size="small" style="margin-top: 16px">
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'probability'">
                <a-progress :percent="record.probability * 100" :status="record.probability > 0.6 ? 'exception' : 'normal'" size="small" />
              </template>
              <template v-else-if="column.key === 'type'">
                <a-tag :color="getRetributionTypeColor(record.type)">
                  {{ getRetributionTypeName(record.type) }}
                </a-tag>
              </template>
              <template v-else-if="column.key === 'level'">
                <a-tag :color="getKarmaLevel(record.totalScore).color">
                  {{ getKarmaLevel(record.totalScore).level }}
                </a-tag>
              </template>
            </template>
          </a-table>
        </a-card>
      </a-col>
    </a-row>

    <!-- 规则编辑弹窗 -->
    <a-modal v-model:open="showRuleModal" :title="`编辑${ruleEditType === 'good' ? '善行' : '恶行'}规则`" @ok="saveRule">
      <a-form ref="ruleFormRef" :model="ruleFormData" layout="vertical">
        <a-form-item label="规则名称" name="name">
          <a-input v-model:value="ruleFormData.name" placeholder="请输入规则名称" />
        </a-form-item>

        <a-form-item label="积分值" name="score">
          <a-input-number v-model:value="ruleFormData.score" placeholder="请输入积分值" style="width: 100%" />
        </a-form-item>

        <a-form-item label="类别" name="category">
          <a-input v-model:value="ruleFormData.category" placeholder="请输入类别" />
        </a-form-item>

        <a-form-item label="等级" name="level">
          <a-select v-model:value="ruleFormData.level" placeholder="请选择等级">
            <a-select-option value="轻微">轻微</a-select-option>
            <a-select-option value="中等">中等</a-select-option>
            <a-select-option value="重大">重大</a-select-option>
            <a-select-option value="极重">极重</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive, nextTick, watch } from 'vue'
import { message } from 'ant-design-vue'
import { LeftOutlined } from '@ant-design/icons-vue'
import { useRouter } from 'vue-router'
import { useKarmaStore } from '@/stores'
import * as echarts from 'echarts'

// 状态管理
const karmaStore = useKarmaStore()
const router = useRouter()

// 响应式数据
const selectedPerson = ref(null)
const predictionPerson = ref(null)
const showRuleModal = ref(false)
const ruleEditType = ref('good')
const ruleEditKey = ref('')
const ruleFormRef = ref()
const overallTrendChart = ref()
const distributionChart = ref()
const predictionChart = ref()
const activeTab = ref('overall')
const chartsLoading = ref(true)

// 规则表单数据
const ruleFormData = reactive({
  name: '',
  score: 0,
  category: '',
  level: '轻微'
})

// 计算属性 - 保持响应性
const karmaRecords = computed(() => karmaStore.karmaRecords)
const karmaRules = computed(() => karmaStore.karmaRules)
const karmaByPerson = computed(() => karmaStore.karmaByPerson)
const { predictRetribution: predictRetributionFromStore, calculateKarmaBalance, getKarmaLevel } = karmaStore

// 所有人员列表
const allPersons = computed(() => karmaByPerson.value)

// 有恶行的人员列表
const evilPersons = computed(() => karmaByPerson.value.filter((person) => person.totalScore < 0).sort((a, b) => a.totalScore - b.totalScore))

// 选中人员的业力数据
const selectedPersonData = ref(null)

// 报应预测结果
const retributionPrediction = ref(null)

// 所有报应预测结果
const allRetributionPredictions = computed(() => {
  return evilPersons.value
    .map((person) => {
      const prediction = predictRetributionFromStore(person.personId)
      return {
        personId: person.personId,
        personName: person.personName,
        totalScore: person.totalScore,
        ...prediction
      }
    })
    .filter((p) => p.type) // 只显示有预测结果的
})

// 统计数据
const totalCalculations = computed(() => karmaByPerson.value.length * 10) // 模拟计算次数
const predictionAccuracy = computed(() => 87.5) // 模拟预测准确率
const activeRulesCount = computed(() => Object.keys(karmaRules.value.goodDeeds).length + Object.keys(karmaRules.value.badDeeds).length)
const pendingRetributionCount = computed(() => allRetributionPredictions.value.length)

// 善行规则数据
const goodRulesData = computed(() =>
  Object.entries(karmaRules.value.goodDeeds).map(([key, rule]) => ({
    key,
    ...rule
  }))
)

// 恶行规则数据
const badRulesData = computed(() =>
  Object.entries(karmaRules.value.badDeeds).map(([key, rule]) => ({
    key,
    ...rule
  }))
)

// 表格列配置
const goodRulesColumns = [
  { title: '规则名称', dataIndex: 'name', key: 'name' },
  { title: '积分', key: 'score', width: 80, align: 'center' },
  { title: '类别', dataIndex: 'category', key: 'category' },
  { title: '等级', key: 'level', width: 80, align: 'center' },
  { title: '操作', key: 'actions', width: 80, align: 'center' }
]

const badRulesColumns = [
  { title: '规则名称', dataIndex: 'name', key: 'name' },
  { title: '积分', key: 'score', width: 80, align: 'center' },
  { title: '类别', dataIndex: 'category', key: 'category' },
  { title: '等级', key: 'level', width: 80, align: 'center' },
  { title: '操作', key: 'actions', width: 80, align: 'center' }
]

const retributionColumns = [
  { title: '人员姓名', dataIndex: 'personName', key: 'personName' },
  { title: '当前业力', dataIndex: 'totalScore', key: 'totalScore', align: 'center' },
  { title: '业力等级', key: 'level', align: 'center' },
  { title: '报应类型', key: 'type', align: 'center' },
  { title: '时间范围', dataIndex: 'timeRange', key: 'timeRange' },
  { title: '发生概率', key: 'probability', width: 120 },
  { title: '严重程度', dataIndex: 'severity', key: 'severity', align: 'center' }
]

// 方法
const getLevelColor = (level) => {
  const colors = {
    轻微: 'blue',
    中等: 'orange',
    重大: 'red',
    极重: 'purple'
  }
  return colors[level] || 'blue'
}

const getRetributionTypeName = (type) => {
  const names = {
    immediate: '立即报应',
    shortTerm: '短期报应',
    mediumTerm: '中期报应',
    longTerm: '来世报应'
  }
  return names[type] || '未知'
}

const getRetributionTypeColor = (type) => {
  const colors = {
    immediate: 'red',
    shortTerm: 'orange',
    mediumTerm: 'blue',
    longTerm: 'purple'
  }
  return colors[type] || 'blue'
}

const getRetributionAlertType = (probability) => {
  if (probability >= 0.8) return 'error'
  if (probability >= 0.6) return 'warning'
  if (probability >= 0.4) return 'info'
  return 'success'
}

const getCurrentPersonName = (personId) => {
  const person = allPersons.value.find((p) => p.personId === personId)
  return person?.personName || '未知'
}

const calculatePersonKarma = () => {
  if (!selectedPerson.value) return

  const balance = calculateKarmaBalance(selectedPerson.value)
  selectedPersonData.value = balance
}

const predictRetributionForPerson = () => {
  if (!predictionPerson.value) return

  const prediction = predictRetributionFromStore(predictionPerson.value)
  retributionPrediction.value = prediction
}

const batchPredictRetribution = () => {
  // 批量预测逻辑已在 computed 中处理
  message.success(`已为 ${allRetributionPredictions.value.length} 人生成报应预测`)
}

const editRule = (type, key) => {
  ruleEditType.value = type
  ruleEditKey.value = key

  const rule = type === 'good' ? karmaRules.value.goodDeeds[key] : karmaRules.value.badDeeds[key]
  Object.assign(ruleFormData, rule)

  showRuleModal.value = true
}

const saveRule = () => {
  // 这里可以添加保存规则的逻辑
  message.success('规则保存成功')
  showRuleModal.value = false
}

// 返回上级页面
const goBack = () => {
  router.push('/karma')
}

// 处理标签页切换
const handleTabChange = (key) => {
  console.log('Tab changed to:', key)
  // 延迟执行以确保DOM已更新
  nextTick(() => {
    setTimeout(() => {
      switch (key) {
        case 'overall':
          console.log('重新初始化整体趋势图表')
          if (overallTrendChart.value) {
            // 强制重置容器宽度
            overallTrendChart.value.style.width = '100%'
            overallTrendChart.value.style.minWidth = '100%'
          }
          setTimeout(() => initOverallTrendChart(), 50)
          break
        case 'distribution':
          console.log('重新初始化等级分布图表')
          if (distributionChart.value) {
            // 强制重置容器宽度
            distributionChart.value.style.width = '100%'
            distributionChart.value.style.minWidth = '100%'
          }
          setTimeout(() => initDistributionChart(), 50)
          break
        case 'prediction':
          console.log('重新初始化预测图表')
          if (predictionChart.value) {
            // 强制重置容器宽度
            predictionChart.value.style.width = '100%'
            predictionChart.value.style.minWidth = '100%'
          }
          setTimeout(() => initPredictionChart(), 50)
          break
      }
    }, 100)
  })
}

// 生命周期
onMounted(async () => {
  console.log('Engine组件挂载开始')
  console.log('ECharts是否可用:', typeof echarts !== 'undefined')

  chartsLoading.value = true

  try {
    await karmaStore.fetchKarmaRecords()
    console.log('数据加载完成，karmaRecords:', karmaRecords.value.length)
    console.log('karmaByPerson:', karmaByPerson.value.length)

    // 延迟渲染所有图表，确保DOM完全就绪
    setTimeout(() => {
      console.log('开始初始化图表，当前激活tab:', activeTab.value)
      console.log('DOM元素状态:')
      console.log('overallTrendChart:', overallTrendChart.value)
      console.log('distributionChart:', distributionChart.value)
      console.log('predictionChart:', predictionChart.value)

      // 强制初始化所有图表，分别延迟以确保完全渲染
      setTimeout(() => initOverallTrendChart(), 100)
      setTimeout(() => initDistributionChart(), 200)
      setTimeout(() => initPredictionChart(), 300)

      // 图表初始化完成后取消加载状态
      setTimeout(() => {
        chartsLoading.value = false
      }, 800)
    }, 1500) // 增加延迟时间到1.5秒
  } catch (error) {
    console.error('数据加载失败:', error)
    chartsLoading.value = false
  }
})

// 监听数据变化重新渲染图表
watch(
  [karmaRecords, karmaByPerson],
  () => {
    nextTick(() => {
      setTimeout(() => {
        initOverallTrendChart()
        initDistributionChart()
        initPredictionChart()
      }, 100)
    })
  },
  { deep: true }
)

// 预测报应的处理函数
const handlePredictRetribution = () => {
  predictRetributionForPerson()
}

// 图表数据计算
const overallTrendData = computed(() => {
  // 如果没有数据，返回空数据
  if (karmaRecords.value.length === 0) {
    return { months: [], goodScores: [], badScores: [] }
  }

  // 生成最近6个月的业力趋势数据
  const months = []
  const goodScores = []
  const badScores = []

  // 计算总的善恶分数
  const totalGoodScore = karmaRecords.value.filter((r) => r.score > 0).reduce((sum, r) => sum + r.score, 0)
  const totalBadScore = Math.abs(karmaRecords.value.filter((r) => r.score < 0).reduce((sum, r) => sum + r.score, 0))

  for (let i = 5; i >= 0; i--) {
    const month = new Date()
    month.setMonth(month.getMonth() - i)
    const monthName = `${month.getMonth() + 1}月`
    months.push(monthName)

    // 为了演示，将总分数分布到各个月份，并加入一些随机变化
    const baseGood = Math.floor(totalGoodScore / 6)
    const baseBad = Math.floor(totalBadScore / 6)
    const goodScore = baseGood + Math.floor(Math.random() * (baseGood * 0.5))
    const badScore = baseBad + Math.floor(Math.random() * (baseBad * 0.5))

    goodScores.push(goodScore)
    badScores.push(badScore)
  }

  return { months, goodScores, badScores }
})

const distributionData = computed(() => {
  console.log('计算等级分布数据，karmaByPerson长度:', karmaByPerson.value?.length)

  if (!karmaByPerson.value || karmaByPerson.value.length === 0) {
    // 提供默认数据以确保图表能显示
    console.log('使用默认数据')
    return [
      { name: '圣人', value: 1 },
      { name: '善人', value: 5 },
      { name: '凡人', value: 12 },
      { name: '恶人', value: 3 },
      { name: '罪人', value: 1 }
    ]
  }

  const distribution = {}
  karmaByPerson.value.forEach((person) => {
    const level = getKarmaLevel(person.totalScore)
    console.log(`${person.personName}: ${person.totalScore} -> ${level.level}`)
    if (!distribution[level.level]) {
      distribution[level.level] = 0
    }
    distribution[level.level]++
  })

  // 确保所有等级都有数据，没有的补0
  const allLevels = ['圣人', '善人', '凡人', '恶人', '罪人']
  allLevels.forEach((level) => {
    if (!distribution[level]) {
      distribution[level] = 0
    }
  })

  const result = Object.entries(distribution)
    .map(([name, value]) => ({ name, value }))
    .filter((item) => item.value > 0) // 只显示有人数的等级
    .sort((a, b) => {
      // 按等级排序
      const order = ['圣人', '善人', '凡人', '恶人', '罪人']
      return order.indexOf(a.name) - order.indexOf(b.name)
    })

  console.log('等级分布结果:', result)
  return result
})

// 初始化整体趋势图表
const initOverallTrendChart = () => {
  if (!overallTrendChart.value) return

  // 强制设置容器宽度为100%
  overallTrendChart.value.style.width = '100%'
  overallTrendChart.value.style.minWidth = '100%'

  // 等待DOM更新后再检查尺寸
  nextTick(() => {
    const containerWidth = overallTrendChart.value.clientWidth || overallTrendChart.value.offsetWidth
    const parentWidth = overallTrendChart.value.parentElement?.clientWidth
    console.log('图表容器宽度:', containerWidth, '父容器宽度:', parentWidth)

    // 如果容器宽度不正确，强制设置
    if (containerWidth < 300 && parentWidth) {
      overallTrendChart.value.style.width = parentWidth + 'px'
    }

    const chart = echarts.init(overallTrendChart.value)
    const { months, goodScores, badScores } = overallTrendData.value

    const option = {
      backgroundColor: 'transparent',
      title: {
        text: '善恶业力整体趋势',
        left: 'center',
        top: 10,
        textStyle: {
          fontSize: 18,
          fontWeight: 'bold',
          color: '#d4990a',
          textShadowColor: 'rgba(212, 153, 10, 0.5)',
          textShadowOffsetX: 0,
          textShadowOffsetY: 0,
          textShadowBlur: 10
        }
      },
      tooltip: {
        trigger: 'axis',
        backgroundColor: 'rgba(0, 0, 0, 0.8)',
        borderColor: 'rgba(212, 153, 10, 0.5)',
        borderWidth: 1,
        textStyle: {
          color: '#fff'
        },
        formatter: function (params) {
          let result = `<div style="font-weight: bold; margin-bottom: 5px;">${params[0].name}</div>`
          params.forEach((param) => {
            const color = param.color
            const value = param.value
            result += `<div style="margin: 2px 0;">
            <span style="display: inline-block; width: 10px; height: 10px; background: ${color}; border-radius: 50%; margin-right: 5px;"></span>
            ${param.seriesName}: <span style="color: ${color}; font-weight: bold;">${value}分</span>
          </div>`
          })
          return result
        }
      },
      legend: {
        data: ['善行积分', '恶行积分'],
        top: 40,
        textStyle: {
          color: '#d1d1d1',
          fontSize: 12
        },
        itemGap: 30
      },
      grid: {
        left: '2%',
        right: '2%',
        bottom: '8%',
        top: '18%',
        containLabel: true,
        width: 'auto',
        height: 'auto'
      },
      xAxis: {
        type: 'category',
        data: months,
        axisLine: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.3)'
          }
        },
        axisTick: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.3)'
          }
        },
        axisLabel: {
          color: '#d1d1d1',
          fontSize: 12
        }
      },
      yAxis: {
        type: 'value',
        name: '积分',
        nameTextStyle: {
          color: '#d1d1d1',
          fontSize: 12
        },
        axisLine: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.3)'
          }
        },
        axisTick: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.3)'
          }
        },
        axisLabel: {
          color: '#d1d1d1',
          fontSize: 11
        },
        splitLine: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.1)',
            type: 'dashed'
          }
        }
      },
      series: [
        {
          name: '善行积分',
          type: 'line',
          data: goodScores,
          smooth: true,
          symbol: 'circle',
          symbolSize: 6,
          lineStyle: {
            width: 3,
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 1,
              y2: 0,
              colorStops: [
                { offset: 0, color: '#52c41a' },
                { offset: 1, color: '#73d13d' }
              ]
            }
          },
          itemStyle: {
            color: '#52c41a',
            borderColor: '#fff',
            borderWidth: 2
          },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                { offset: 0, color: 'rgba(82, 196, 26, 0.4)' },
                { offset: 1, color: 'rgba(82, 196, 26, 0.1)' }
              ]
            }
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowColor: '#52c41a'
            }
          }
        },
        {
          name: '恶行积分',
          type: 'line',
          data: badScores,
          smooth: true,
          symbol: 'circle',
          symbolSize: 6,
          lineStyle: {
            width: 3,
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 1,
              y2: 0,
              colorStops: [
                { offset: 0, color: '#ff4d4f' },
                { offset: 1, color: '#ff7875' }
              ]
            }
          },
          itemStyle: {
            color: '#ff4d4f',
            borderColor: '#fff',
            borderWidth: 2
          },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                { offset: 0, color: 'rgba(255, 77, 79, 0.4)' },
                { offset: 1, color: 'rgba(255, 77, 79, 0.1)' }
              ]
            }
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowColor: '#ff4d4f'
            }
          }
        }
      ]
    }
    chart.setOption(option)

    // 强制调整图表大小以适应容器
    nextTick(() => {
      chart.resize()
    })

    window.addEventListener('resize', () => {
      setTimeout(() => {
        chart.resize()
      }, 100)
    })
  }) // 闭合外层的nextTick
}

// 初始化等级分布图表
const initDistributionChart = () => {
  if (!distributionChart.value) {
    console.log('distributionChart DOM元素不存在')
    return
  }

  // 强制设置容器宽度为100%
  distributionChart.value.style.width = '100%'
  distributionChart.value.style.minWidth = '100%'

  try {
    // 确保容器有正确的尺寸
    const containerWidth = distributionChart.value.clientWidth || distributionChart.value.offsetWidth
    const parentWidth = distributionChart.value.parentElement?.clientWidth
    console.log('等级分布图表容器宽度:', containerWidth, '父容器宽度:', parentWidth)

    // 如果容器宽度不正确，强制设置
    if (containerWidth < 300 && parentWidth) {
      distributionChart.value.style.width = parentWidth + 'px'
    }

    // 强制初始化，不检查可见性
    const chart = echarts.init(distributionChart.value, null)
    const data = distributionData.value
    console.log('等级分布数据:', data)

    // 为不同等级定义颜色
    const levelColors = {
      圣人: '#722ed1',
      善人: '#52c41a',
      凡人: '#1890ff',
      恶人: '#fa541c',
      罪人: '#f5222d'
    }

    // 为数据添加颜色
    const coloredData = data.map((item) => ({
      ...item,
      itemStyle: {
        color: {
          type: 'radial',
          x: 0.5,
          y: 0.5,
          r: 0.8,
          colorStops: [
            { offset: 0, color: levelColors[item.name] || '#1890ff' },
            { offset: 1, color: echarts.color.lift(levelColors[item.name] || '#1890ff', -0.3) }
          ]
        },
        borderColor: '#fff',
        borderWidth: 2,
        shadowBlur: 10,
        shadowColor: 'rgba(0, 0, 0, 0.3)'
      }
    }))

    const option = {
      backgroundColor: 'transparent',
      title: {
        text: '业力等级分布',
        textStyle: {
          fontSize: 18,
          fontWeight: 'bold',
          color: '#d4990a',
          textShadowColor: 'rgba(212, 153, 10, 0.5)',
          textShadowOffsetX: 0,
          textShadowOffsetY: 0,
          textShadowBlur: 10
        },
        left: 'center',
        top: 10
      },
      tooltip: {
        trigger: 'item',
        backgroundColor: 'rgba(0, 0, 0, 0.8)',
        borderColor: 'rgba(212, 153, 10, 0.5)',
        borderWidth: 1,
        textStyle: {
          color: '#fff',
          fontSize: 12
        },
        formatter: function (params) {
          return `<div style="font-weight: bold; color: ${params.color};">${params.name}</div>
                  <div style="margin-top: 5px;">
                    人数: <span style="color: #fff; font-weight: bold;">${params.value}人</span><br/>
                    占比: <span style="color: #d4990a; font-weight: bold;">${params.percent}%</span>
                  </div>`
        }
      },
      legend: {
        orient: 'vertical',
        left: '5%',
        top: 'middle',
        textStyle: {
          color: '#d1d1d1',
          fontSize: 12
        },
        formatter: function (name) {
          const item = data.find((d) => d.name === name)
          return `${name} (${item ? item.value : 0}人)`
        }
      },
      series: [
        {
          name: '业力等级',
          type: 'pie',
          radius: ['45%', '75%'],
          center: ['65%', '50%'],
          avoidLabelOverlap: false,
          data: coloredData,
          label: {
            show: true,
            position: 'outside',
            color: '#d1d1d1',
            fontSize: 11,
            formatter: function (params) {
              return `${params.name}\n${params.percent}%`
            }
          },
          labelLine: {
            show: true,
            lineStyle: {
              color: 'rgba(255, 255, 255, 0.3)'
            }
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 15,
              shadowOffsetX: 0,
              shadowColor: 'rgba(212, 153, 10, 0.5)'
            },
            label: {
              show: true,
              fontSize: 14,
              fontWeight: 'bold',
              color: '#d4990a'
            }
          },
          animationType: 'scale',
          animationEasing: 'elasticOut',
          animationDelay: function (idx) {
            return Math.random() * 200
          }
        }
      ]
    }
    chart.setOption(option)

    // 延迟重新调整大小
    setTimeout(() => {
      chart.resize()
    }, 100)

    // 强制调整图表大小以适应容器
    nextTick(() => {
      chart.resize()
    })

    window.addEventListener('resize', () => {
      setTimeout(() => {
        chart.resize()
      }, 100)
    })
  } catch (error) {
    console.error('等级分布图表初始化失败:', error)
  }
}

// 初始化预测图表
const initPredictionChart = () => {
  if (!predictionChart.value) {
    console.log('predictionChart DOM元素不存在')
    return
  }

  // 强制设置容器宽度为100%
  predictionChart.value.style.width = '100%'
  predictionChart.value.style.minWidth = '100%'

  try {
    // 确保容器有正确的尺寸
    const containerWidth = predictionChart.value.clientWidth || predictionChart.value.offsetWidth
    const parentWidth = predictionChart.value.parentElement?.clientWidth
    console.log('预测图表容器宽度:', containerWidth, '父容器宽度:', parentWidth)

    // 如果容器宽度不正确，强制设置
    if (containerWidth < 300 && parentWidth) {
      predictionChart.value.style.width = parentWidth + 'px'
    }

    // 强制初始化，不检查可见性
    const chart = echarts.init(predictionChart.value, null)

    // 基于当前数据计算基础值
    const currentGoodTotal = karmaRecords.value.filter((r) => r.score > 0).reduce((sum, r) => sum + r.score, 0)
    const currentBadTotal = Math.abs(karmaRecords.value.filter((r) => r.score < 0).reduce((sum, r) => sum + r.score, 0))

    // 如果没有历史数据，使用默认值
    const baseGoodMonthly = currentGoodTotal > 0 ? currentGoodTotal / 6 : 100
    const baseBadMonthly = currentBadTotal > 0 ? currentBadTotal / 6 : 60

    console.log('预测基础数据:', { currentGoodTotal, currentBadTotal, baseGoodMonthly, baseBadMonthly })

    // 生成未来6个月的业力预测数据
    const futureMonths = []
    const predictedGood = []
    const predictedBad = []
    const netKarma = []

    for (let i = 1; i <= 6; i++) {
      const month = new Date()
      month.setMonth(month.getMonth() + i)
      let monthName

      // 确保月份正确显示
      if (month.getMonth() + 1 > 12) {
        monthName = `${month.getMonth() + 1 - 12}月`
      } else {
        monthName = `${month.getMonth() + 1}月`
      }
      futureMonths.push(monthName)

      // 基于当前趋势进行预测，加入一些随机变化
      const goodVariation = 0.8 + Math.random() * 0.4 // 0.8-1.2倍变化
      const badVariation = 0.8 + Math.random() * 0.4

      const goodValue = Math.round(baseGoodMonthly * goodVariation)
      const badValue = Math.round(baseBadMonthly * badVariation)

      predictedGood.push(goodValue)
      predictedBad.push(badValue)
      netKarma.push(goodValue - badValue)
    }

    console.log('预测图表数据:', { futureMonths, predictedGood, predictedBad, netKarma })

    const option = {
      backgroundColor: 'transparent',
      title: {
        text: '业力趋势预测',
        textStyle: {
          fontSize: 18,
          fontWeight: 'bold',
          color: '#d4990a',
          textShadowColor: 'rgba(212, 153, 10, 0.5)',
          textShadowOffsetX: 0,
          textShadowOffsetY: 0,
          textShadowBlur: 10
        },
        left: 'center',
        top: 10
      },
      tooltip: {
        trigger: 'axis',
        backgroundColor: 'rgba(0, 0, 0, 0.8)',
        borderColor: 'rgba(212, 153, 10, 0.5)',
        borderWidth: 1,
        textStyle: {
          color: '#fff'
        },
        formatter: function (params) {
          let result = `<div style="font-weight: bold; margin-bottom: 8px; color: #d4990a;">${params[0].name}</div>`
          params.forEach((param) => {
            const color = param.color
            result += `<div style="margin: 3px 0; display: flex; align-items: center;">
              <span style="display: inline-block; width: 12px; height: 12px; background: ${color}; border-radius: 2px; margin-right: 8px;"></span>
              <span style="flex: 1;">${param.seriesName}:</span>
              <span style="color: ${color}; font-weight: bold; margin-left: 8px;">${param.value}分</span>
            </div>`
          })

          // 添加净业力显示
          const goodVal = params.find((p) => p.seriesName === '预测善行')?.value || 0
          const badVal = params.find((p) => p.seriesName === '预测恶行')?.value || 0
          const net = goodVal - badVal
          const netColor = net >= 0 ? '#52c41a' : '#ff4d4f'

          result += `<div style="margin-top: 8px; padding-top: 8px; border-top: 1px solid rgba(255,255,255,0.2);">
            <div style="display: flex; align-items: center;">
              <span style="flex: 1; color: #d1d1d1;">净业力:</span>
              <span style="color: ${netColor}; font-weight: bold; margin-left: 8px;">${net >= 0 ? '+' : ''}${net}分</span>
            </div>
          </div>`

          return result
        }
      },
      legend: {
        data: ['预测善行', '预测恶行', '净业力趋势'],
        top: 40,
        textStyle: {
          color: '#d1d1d1',
          fontSize: 12
        },
        itemGap: 20
      },
      grid: {
        left: '2%',
        right: '2%',
        bottom: '8%',
        top: '20%',
        containLabel: true,
        width: 'auto',
        height: 'auto'
      },
      xAxis: {
        type: 'category',
        data: futureMonths,
        axisLine: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.3)'
          }
        },
        axisTick: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.3)'
          }
        },
        axisLabel: {
          color: '#d1d1d1',
          fontSize: 12
        }
      },
      yAxis: [
        {
          type: 'value',
          name: '预测积分',
          nameTextStyle: {
            color: '#d1d1d1',
            fontSize: 12
          },
          axisLine: {
            lineStyle: {
              color: 'rgba(255, 255, 255, 0.3)'
            }
          },
          axisTick: {
            lineStyle: {
              color: 'rgba(255, 255, 255, 0.3)'
            }
          },
          axisLabel: {
            color: '#d1d1d1',
            fontSize: 11
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(255, 255, 255, 0.1)',
              type: 'dashed'
            }
          }
        }
      ],
      series: [
        {
          name: '预测善行',
          type: 'bar',
          data: predictedGood,
          barWidth: '25%',
          itemStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                { offset: 0, color: '#52c41a' },
                { offset: 1, color: '#389e0d' }
              ]
            },
            borderRadius: [4, 4, 0, 0],
            borderColor: '#fff',
            borderWidth: 1,
            shadowBlur: 5,
            shadowColor: 'rgba(82, 196, 26, 0.3)'
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowColor: 'rgba(82, 196, 26, 0.5)'
            }
          }
        },
        {
          name: '预测恶行',
          type: 'bar',
          data: predictedBad,
          barWidth: '25%',
          itemStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                { offset: 0, color: '#ff7875' },
                { offset: 1, color: '#cf1322' }
              ]
            },
            borderRadius: [4, 4, 0, 0],
            borderColor: '#fff',
            borderWidth: 1,
            shadowBlur: 5,
            shadowColor: 'rgba(255, 120, 117, 0.3)'
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowColor: 'rgba(255, 120, 117, 0.5)'
            }
          }
        },
        {
          name: '净业力趋势',
          type: 'line',
          data: netKarma,
          symbol: 'diamond',
          symbolSize: 8,
          lineStyle: {
            width: 3,
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 1,
              y2: 0,
              colorStops: [
                { offset: 0, color: '#722ed1' },
                { offset: 1, color: '#9254de' }
              ]
            }
          },
          itemStyle: {
            color: '#722ed1',
            borderColor: '#fff',
            borderWidth: 2
          },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                { offset: 0, color: 'rgba(114, 46, 209, 0.3)' },
                { offset: 1, color: 'rgba(114, 46, 209, 0.05)' }
              ]
            }
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowColor: '#722ed1'
            }
          }
        }
      ]
    }
    chart.setOption(option)

    // 延迟重新调整大小
    setTimeout(() => {
      chart.resize()
    }, 100)

    // 强制调整图表大小以适应容器
    nextTick(() => {
      chart.resize()
    })

    window.addEventListener('resize', () => {
      setTimeout(() => {
        chart.resize()
      }, 100)
    })
    console.log('预测图表初始化完成')
  } catch (error) {
    console.error('预测图表初始化失败:', error)
  }
}
</script>

<style lang="scss" scoped>
@use 'sass:color';

.karma-engine-page {
  padding: 24px;
  min-height: 100vh;
  width: 100%;
  box-sizing: border-box;

  // 面包屑导航样式 - 仿照Dashboard
  .breadcrumb-wrapper {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding: 16px 20px;
    background: rgba(255, 255, 255, 0.05);
    border: 1px solid rgba(255, 255, 255, 0.15);
    border-radius: 12px;
    backdrop-filter: blur(10px);

    :deep(.ant-breadcrumb) {
      .ant-breadcrumb-link {
        color: $text-secondary;

        a {
          color: $primary-color;

          &:hover {
            color: color.adjust($primary-color, $lightness: 10%);
          }
        }
      }

      .ant-breadcrumb-separator {
        color: $text-tertiary;
      }
    }

    .back-button {
      color: $primary-color;
      border: none;
      background: transparent;

      &:hover {
        color: lighten($primary-color, 10%);
        background: rgba(114, 46, 209, 0.1);
      }
    }
  }

  // 页面标题样式 - 仿照Dashboard
  .ancient-title {
    text-align: center;
    font-size: 32px;
    font-weight: bold;
    color: $secondary-color;
    margin-bottom: 48px;
    text-shadow: 0 0 20px rgba(212, 153, 10, 0.3);
    font-family: 'PingFang SC', '微软雅黑', sans-serif;
  }

  // 统计卡片区域样式
  .stats-row,
  .function-row,
  .analysis-row,
  .prediction-row {
    margin-bottom: 32px;
  }

  // 统计卡片样式 - 仿照Dashboard
  .stat-card {
    background: rgba(255, 255, 255, 0.03);
    border: 1px solid rgba(255, 255, 255, 0.1);
    border-radius: 16px;
    padding: 24px;
    height: 120px;
    display: flex;
    align-items: center;
    justify-content: center;
    backdrop-filter: blur(10px);
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;

    &::before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      height: 3px;
      background: linear-gradient(90deg, transparent, $secondary-color, transparent);
      opacity: 0.6;
    }

    :deep(.ant-statistic) {
      text-align: center;

      .ant-statistic-title {
        color: $text-secondary;
        font-size: 14px;
        margin-bottom: 8px;
      }

      .ant-statistic-content {
        .ant-statistic-content-value {
          color: currentColor;
          font-weight: bold;
        }
      }
    }
  }

  // 功能卡片样式 - 仿照Dashboard section样式
  .rules-card,
  .calculator-card,
  .trend-card,
  .prediction-card {
    background: rgba(255, 255, 255, 0.05);
    border: 1px solid rgba(255, 255, 255, 0.15);
    border-radius: 16px;
    backdrop-filter: blur(10px);
    width: 100%;
    box-sizing: border-box;

    :deep(.ant-card-head) {
      border-bottom: 1px solid rgba(255, 255, 255, 0.1);
      background: transparent;

      .ant-card-head-title {
        color: $text-primary;
        font-size: 18px;
        font-weight: 600;
      }
    }

    :deep(.ant-card-body) {
      color: $text-primary;
    }
  }

  // 业力计算结果样式
  .karma-calculation-result {
    margin-top: 16px;
    padding: 20px;
    background: rgba(255, 255, 255, 0.08);
    border: 1px solid rgba(255, 255, 255, 0.15);
    border-radius: 12px;
    backdrop-filter: blur(10px);

    :deep(.ant-descriptions) {
      .ant-descriptions-header {
        .ant-descriptions-title {
          color: $text-primary;
          font-size: 16px;
          font-weight: 600;
        }
      }

      .ant-descriptions-item-label {
        color: $text-secondary;
      }

      .ant-descriptions-item-content {
        color: $text-primary;
      }
    }

    :deep(.ant-progress) {
      .ant-progress-text {
        color: $text-primary;
      }
    }
  }

  // 报应结果样式
  .retribution-result {
    margin-bottom: 16px;

    :deep(.ant-alert) {
      background: rgba(255, 255, 255, 0.08);
      border: 1px solid rgba(255, 255, 255, 0.15);
      border-radius: 12px;

      .ant-alert-message {
        color: $text-primary;
      }

      .ant-alert-description {
        color: $text-secondary;
      }
    }
  }

  // 分数样式
  .score-positive {
    color: #52c41a;
    font-weight: bold;
  }

  .score-negative {
    color: #f5222d;
    font-weight: bold;
  }

  // 表格样式调整
  :deep(.ant-table) {
    background: transparent;

    .ant-table-container {
      background: transparent;
    }

    .ant-table-thead > tr > th {
      background: rgba(255, 255, 255, 0.08);
      border-bottom: 1px solid rgba(255, 255, 255, 0.1);
      color: $text-primary;
    }

    .ant-table-tbody > tr > td {
      background: transparent;
      border-bottom: 1px solid rgba(255, 255, 255, 0.05);
      color: $text-secondary;
    }

    .ant-table-tbody > tr:hover > td {
      background: rgba(255, 255, 255, 0.05);
    }
  }

  // 标签页样式
  :deep(.ant-tabs) {
    .ant-tabs-nav {
      &::before {
        border-bottom: 1px solid rgba(255, 255, 255, 0.1);
      }

      .ant-tabs-nav-wrap {
        .ant-tabs-nav-list {
          .ant-tabs-tab {
            color: $text-secondary;
            padding: 12px 24px;
            margin: 0 8px;
            border-radius: 8px 8px 0 0;
            background: rgba(255, 255, 255, 0.02);
            border: 1px solid rgba(255, 255, 255, 0.05);
            border-bottom: none;
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;

            &::before {
              content: '';
              position: absolute;
              top: 0;
              left: 0;
              width: 100%;
              height: 2px;
              background: linear-gradient(90deg, transparent, rgba(212, 153, 10, 0.5), transparent);
              opacity: 0;
              transition: opacity 0.3s ease;
            }

            .ant-tabs-tab-btn {
              font-weight: 500;
              font-size: 14px;
            }

            &:hover {
              color: $primary-color;
              background: rgba(114, 46, 209, 0.08);
              border-color: rgba(114, 46, 209, 0.2);
              transform: translateY(-2px);

              &::before {
                opacity: 1;
              }
            }

            &.ant-tabs-tab-active {
              color: $secondary-color;
              background: rgba(212, 153, 10, 0.1);
              border-color: rgba(212, 153, 10, 0.3);
              box-shadow: 0 4px 12px rgba(212, 153, 10, 0.2);

              &::before {
                opacity: 1;
                background: linear-gradient(90deg, $secondary-color, color.adjust($secondary-color, $lightness: 10%), $secondary-color);
              }

              .ant-tabs-tab-btn {
                font-weight: 600;
                text-shadow: 0 0 8px rgba(212, 153, 10, 0.5);
              }
            }
          }
        }
      }
    }

    .ant-tabs-ink-bar {
      background: linear-gradient(90deg, $secondary-color, color.adjust($secondary-color, $lightness: 10%));
      height: 3px;
      border-radius: 2px;
      box-shadow: 0 0 8px rgba(212, 153, 10, 0.5);
    }

    .ant-tabs-content-holder {
      width: 100%;

      .ant-tabs-content {
        color: $text-primary;
        padding-top: 24px;
        width: 100%;

        .ant-tabs-tabpane {
          animation: fadeInUp 0.5s ease;
          width: 100%;
        }
      }
    }
  }

  // 标签页内容淡入动画
  @keyframes fadeInUp {
    from {
      opacity: 0;
      transform: translateY(20px);
    }
    to {
      opacity: 1;
      transform: translateY(0);
    }
  }

  // 表单样式
  :deep(.ant-form) {
    .ant-form-item-label > label {
      color: $text-primary;
    }
  }

  // 输入框和选择器样式
  :deep(.ant-input),
  :deep(.ant-select-selector),
  :deep(.ant-input-number),
  :deep(.ant-picker) {
    background: rgba(255, 255, 255, 0.08);
    border-color: rgba(255, 255, 255, 0.2);
    color: $text-primary;

    &:hover {
      border-color: $primary-color;
    }

    &:focus {
      border-color: $primary-color;
      box-shadow: 0 0 0 2px rgba(114, 46, 209, 0.2);
    }
  }

  :deep(.ant-input::placeholder) {
    color: $text-tertiary;
  }

  :deep(.ant-select) {
    .ant-select-selection-placeholder {
      color: $text-tertiary;
    }

    .ant-select-arrow {
      color: $text-secondary;
    }
  }

  // 按钮样式调整
  :deep(.ant-btn) {
    &.ant-btn-primary {
      background: $primary-color;
      border-color: $primary-color;

      &:hover {
        background: color.adjust($primary-color, $lightness: 10%);
        border-color: color.adjust($primary-color, $lightness: 10%);
      }
    }

    &.ant-btn-link {
      color: $primary-color;

      &:hover {
        color: color.adjust($primary-color, $lightness: 10%);
      }
    }

    &:not(.ant-btn-primary):not(.ant-btn-link) {
      background: rgba(255, 255, 255, 0.08);
      border-color: rgba(255, 255, 255, 0.2);
      color: $text-primary;

      &:hover {
        background: rgba(255, 255, 255, 0.15);
        border-color: $primary-color;
        color: $primary-color;
      }
    }
  }

  // 进度条样式
  :deep(.ant-progress) {
    .ant-progress-text {
      color: $text-primary;
    }
  }

  // 标签样式
  :deep(.ant-tag) {
    background: rgba(255, 255, 255, 0.1);
    border-color: rgba(255, 255, 255, 0.2);
    color: $text-primary;
  }

  // 模态框样式
  :deep(.ant-modal) {
    .ant-modal-content {
      background: rgba(30, 30, 35, 0.95);
      backdrop-filter: blur(20px);
      border: 1px solid rgba(255, 255, 255, 0.15);
    }

    .ant-modal-header {
      background: transparent;
      border-bottom: 1px solid rgba(255, 255, 255, 0.1);

      .ant-modal-title {
        color: $text-primary;
      }
    }

    .ant-modal-body {
      color: $text-primary;
    }

    .ant-modal-footer {
      border-top: 1px solid rgba(255, 255, 255, 0.1);
      background: transparent;
    }
  }

  // 图表容器样式
  .chart-container {
    padding: 16px;
    background: rgba(255, 255, 255, 0.02);
    border: 1px solid rgba(255, 255, 255, 0.08);
    border-radius: 12px;
    backdrop-filter: blur(10px);
    position: relative;
    overflow: hidden;
    width: 100%;
    box-sizing: border-box;

    &::before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      height: 2px;
      background: linear-gradient(90deg, transparent, rgba(212, 153, 10, 0.5), transparent);
      opacity: 0.8;
    }

    &::after {
      content: '';
      position: absolute;
      top: 10px;
      right: 10px;
      width: 40px;
      height: 40px;
      background: radial-gradient(circle, rgba(212, 153, 10, 0.2), transparent);
      border-radius: 50%;
      opacity: 0.6;
      animation: pulse 3s ease-in-out infinite;
    }

    .echarts-wrapper {
      height: 450px;
      width: 100%;
      border-radius: 8px;
      background: rgba(255, 255, 255, 0.01);
      border: 1px solid rgba(255, 255, 255, 0.05);
      transition: all 0.3s ease;
      position: relative;
      box-sizing: border-box;
      min-width: 0; // 防止flex容器中的收缩

      &:hover {
        border-color: rgba(212, 153, 10, 0.3);
        background: rgba(255, 255, 255, 0.03);
        box-shadow: 0 8px 32px rgba(212, 153, 10, 0.1);
        transform: translateY(-2px);
      }

      // 为echarts图表添加内部装饰
      &::before {
        content: '';
        position: absolute;
        top: 8px;
        left: 8px;
        right: 8px;
        bottom: 8px;
        border: 1px solid rgba(212, 153, 10, 0.1);
        border-radius: 6px;
        pointer-events: none;
        z-index: 0;
      }
    }

    .chart-loading {
      height: 450px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      background: rgba(255, 255, 255, 0.01);
      border: 1px solid rgba(255, 255, 255, 0.05);
      border-radius: 8px;
      position: relative;

      .custom-spinner {
        font-size: 32px;
        animation: rotate 2s linear infinite;
        display: inline-block;
      }

      p {
        margin-top: 16px;
        color: $text-secondary;
        font-size: 14px;
        opacity: 0.8;
        animation: fadeInOut 2s ease-in-out infinite;
      }

      :deep(.ant-spin) {
        .ant-spin-dot {
          display: none; // 隐藏默认的loading
        }
      }
    }

    .chart-description {
      margin-top: 16px;
      padding: 12px 16px;
      background: rgba(255, 255, 255, 0.03);
      border: 1px solid rgba(255, 255, 255, 0.1);
      border-radius: 8px;
      text-align: center;
      position: relative;

      &::before {
        content: '📊';
        position: absolute;
        left: 12px;
        top: 50%;
        transform: translateY(-50%);
        font-size: 14px;
        opacity: 0.5;
      }

      p {
        margin: 0;
        color: $text-secondary;
        font-size: 13px;
        line-height: 1.5;
        opacity: 0.8;
        padding-left: 24px;
      }
    }
  }

  // 脉动动画
  @keyframes pulse {
    0%,
    100% {
      opacity: 0.6;
      transform: scale(1);
    }
    50% {
      opacity: 0.3;
      transform: scale(1.2);
    }
  }

  // 旋转动画
  @keyframes rotate {
    from {
      transform: rotate(0deg);
    }
    to {
      transform: rotate(360deg);
    }
  }

  // 淡入淡出动画
  @keyframes fadeInOut {
    0%,
    100% {
      opacity: 0.8;
    }
    50% {
      opacity: 0.4;
    }
  }

  // 为不同标签页添加特殊效果
  :deep(.ant-tabs-tabpane) {
    &[data-node-key='overall'] .chart-container::after {
      background: radial-gradient(circle, rgba(82, 196, 26, 0.2), rgba(255, 77, 79, 0.2), transparent);
    }

    &[data-node-key='distribution'] .chart-container::after {
      background: radial-gradient(circle, rgba(114, 46, 209, 0.2), transparent);
    }

    &[data-node-key='prediction'] .chart-container::after {
      background: radial-gradient(circle, rgba(24, 144, 255, 0.2), rgba(114, 46, 209, 0.2), transparent);
    }
  }
}

// 响应式适配
@media (max-width: 1200px) {
  .karma-engine-page {
    .stat-card {
      height: 100px;
      padding: 20px;
    }
  }
}

@media (max-width: 768px) {
  .karma-engine-page {
    padding: 16px;

    .stats-row,
    .function-row,
    .analysis-row,
    .prediction-row {
      margin-bottom: 24px;
    }

    .stat-card {
      height: 80px;
      padding: 16px;
    }

    .breadcrumb-wrapper {
      padding: 12px 16px;
      flex-direction: column;
      gap: 12px;
      align-items: flex-start;

      .back-button {
        align-self: flex-end;
      }
    }
  }
}
</style>
